package pl.poznan.put.cs.idss.students.coolring.ui.components;

import java.awt.FlowLayout;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;

import pl.poznan.put.cs.idss.students.coolring.core.IAlgorithm;
import pl.poznan.put.cs.idss.students.coolring.core.impl.KornelColoring;
import pl.poznan.put.cs.idss.students.coolring.i18n.Messages;
import pl.poznan.put.cs.idss.students.coolring.properties.Properties;
import pl.poznan.put.cs.idss.students.coolring.ui.GeneralWindow;

public class Toolbox extends JPanel implements ActionListener {

	private static final long serialVersionUID = 6716778850902902694L;

	Logger log = Logger.getLogger("pl.poznan.put.cs.idss.students.coolring");

	private List<ImageButton> buttonsList = new ArrayList<ImageButton>();
	private int currentVerticalPosition = 0;

	private GeneralWindow parentFrame;

	public Toolbox(GeneralWindow parent) {

		parentFrame = parent;

		setLayout(new FlowLayout(0, 0, 0));

		setSize(Properties.number("toolbox_width"),
				Properties.number("generalwindow_height"));

		setLocation(0, 0);

		addSpacer(Toolbox.class.getResource(Properties.get("spacer")));

		addButton(Toolbox.class.getResource(Properties.get("button_open")),
				Toolbox.class.getResource(Properties.get("button_open_hover")),
				"chooseFile", Messages.get("UI.button_open_tooltip"));

		addSpacer(Toolbox.class.getResource(Properties.get("spacer")));

		addButton(Toolbox.class.getResource(Properties.get("button_save")),
				Toolbox.class.getResource(Properties.get("button_save_hover")),
				"saveFile", Messages.get("UI.button_save_tooltip"));

		addSpacer(Toolbox.class.getResource(Properties.get("spacer")));

		addButton(Toolbox.class.getResource(Properties.get("button_undo")),
				Toolbox.class.getResource(Properties.get("button_undo_hover")),
				"undo", Messages.get("UI.button_undo_tooltip"));

		addSpacer(Toolbox.class.getResource(Properties.get("spacer")));

		addButton(
				Toolbox.class.getResource(Properties.get("button_color")),
				Toolbox.class.getResource(Properties.get("button_color_hover")),
				"color", Messages.get("UI.button_color_tooltip"));

		addSpacer(Toolbox.class.getResource(Properties.get("spacer")));

		setVisible(true);

		drawElements();

	}

	public void addSpacer(URL image) {
		ImageButton spacer = new ImageButton();
		spacer.setImage(Toolkit.getDefaultToolkit().getImage(image));
		buttonsList.add(spacer);
	}

	public void addButton(URL image, URL hoverImage, String actionCommand,
			String tooltip) {

		ImageButton button = new ImageButton();

		if (image != null) {
			button.setImage(Toolkit.getDefaultToolkit().getImage(image));
		}

		if (hoverImage != null) {
			button.setHoverImage(Toolkit.getDefaultToolkit().getImage(
					hoverImage));
		}

		if (actionCommand != null) {
			button.setActionCommand(actionCommand);
		}

		if (tooltip != null) {
			button.setToolTipText(tooltip);
		}

		buttonsList.add(button);

	}

	private void drawElements() {
		for (JButton button : buttonsList) {
			button.setLocation(0, currentVerticalPosition);
			button.addActionListener(this);
			button.setVisible(true);
			button.setContentAreaFilled(false);
			button.setFocusPainted(false);
			add(button);
			currentVerticalPosition += button.getHeight();
		}
	}

	public void actionPerformed(ActionEvent e) {

		if ("close".equals(e.getActionCommand())) {
			log.info("Closing application");
			parentFrame.dispose();
		} else if ("chooseFile".equals(e.getActionCommand())) {
			chooseFile();
		} else if ("undo".equals(e.getActionCommand())) {
			parentFrame.getCanvas().undo();
		} else if ("color".equals(e.getActionCommand())) {
			IAlgorithm alg = new KornelColoring();
			alg.setImage(parentFrame.getCanvas().getImage());
			alg.setPointsList(parentFrame.getCanvas().getPointsList());
			alg.run();
			while (alg.getProgress() < 1)
				;
			parentFrame.getCanvas().setImage(alg.getReslt());
			parentFrame.getCanvas().getPointsList().clear();
			parentFrame.getCanvas().repaint();
		} else if("saveFile".equals(e.getActionCommand())){
			saveFile(parentFrame.getCanvas().getImage());
		}
		else {
			log.severe("Action " + e.getActionCommand() + " not supported!");
		}

	}

	private void saveFile(Image image) {
		JFileChooser chooser = new JFileChooser();
		chooser.setDialogTitle(Messages
				.get("UI.application_choose_file_dialog"));
	//	FileFilter imageFilter = new FileNameExtensionFilter("Image files",
	//			ImageIO.getReaderFileSuffixes());
		String fileFormat = "jpg";
	//	chooser.setFileFilter(imageFilter);
		File file = new File("coloredImage");
		chooser.setSelectedFile(file);
		if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
			log.info("Choose file dialog; image: "
					+ chooser.getSelectedFile().getName());
			try {
				file = new File(chooser.getSelectedFile().getAbsolutePath()+"."+fileFormat);
				int scaleX = 640; int scaleY = 480;
				image = image.getScaledInstance(scaleX, scaleY, Image.SCALE_SMOOTH);
				BufferedImage buffered = new BufferedImage(scaleX, scaleY, BufferedImage.TYPE_INT_RGB);
				buffered.getGraphics().drawImage(image, 0, 0 , null);
				
				
			  //  BufferedImage bi = (BufferedImage) image;
			    ImageIO.write(buffered, fileFormat, file);
			} catch (IOException e) {
			    e.printStackTrace();
			}
		}
	}

	private void chooseFile() {
		JFileChooser chooser = new JFileChooser();
		chooser.setDialogTitle(Messages
				.get("UI.application_choose_file_dialog"));
		FileFilter imageFilter = new FileNameExtensionFilter("Image files",
				ImageIO.getReaderFileSuffixes());
		chooser.setFileFilter(imageFilter);
		if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
			log.info("Choose file dialog; image: "
					+ chooser.getSelectedFile().getName());
			try {
				parentFrame.getCanvas().drawImage(
						chooser.getSelectedFile().getAbsolutePath());
				parentFrame.setTitle(Messages.get("UI.application_name") + ": "
						+ chooser.getSelectedFile().getName());
			} catch (Exception ex) {
				JOptionPane.showMessageDialog(null,
						Messages.get("UI.error_msg_not_an_image"),
						Messages.get("UI.application_internal_error_title"),
						JOptionPane.ERROR_MESSAGE);
			}
		} else {
			log.info("Cannot open choosed file.");
		}
	}

}
